<template>
	<main class="main-page" id="">
		<template v-if="showHeader">
			<section class="page-section mb-3">
				<div class="container-fluid">
					<div class="grid justify-content-between align-items-center">
						<div class="col ">
							<div class=" text-2xl text-primary font-bold">
								{{ $t('courses') }}
							</div>
						</div>
						<div class="col-fixed ">
							<template v-if="auth.canView('courses/add')">
								<router-link :to="`/courses/add`">
									<Button :label="$t('addNewCours')" icon="pi pi-plus" type="button"
										class="p-button w-full bg-primary " />
								</router-link>
							</template>
						</div>
						<div class="col-fixed ">
							<template v-if="auth.canView('courses/bulk-import')">
								<Button :label="$t('downloadTemplate')" icon="pi pi-download" type="button"
									class="p-button w-full bg-primary ml-2" @click="downloadTemplate" />
							</template>
						</div>
						<div class="col-fixed ">
							<template v-if="auth.canView('courses/bulk-import')">
								<Button :label="$t('importCourses')" icon="pi pi-upload" type="button"
									class="p-button w-full bg-primary ml-2" @click="showImportDialog = true" />
							</template>
						</div>
						<div class="col-12 md:col-3 ">
							<span class="p-input-icon-left w-full">
								<i class="pi pi-search" />
								<InputText :placeholder="$t('search')" class="w-full" :value="filters.search.value"
									@input="debounce(() => { filters.search.value = $event.target.value })" />
							</span>
						</div>

					</div>
				</div>
			</section>
		</template>
		<section class="page-section ">
			<div class="container-fluid">
				<div class="grid ">
					<div class="col comp-grid">
						<div class="flex align-items-center">
							<filter-tags :controller="page.filterController" />
						</div>
						<div>
							<template v-if="showBreadcrumbs && $route.query.tag && !isSubPage">
								<Breadcrumb :home="{ icon: 'pi pi-home', to: '/courses' }" :model="pageBreadCrumb" />
							</template>
							<!-- page records template -->
							<div class="page-records">
								<div v-if="records.length" class="grid">
									<div v-for="course in records" :key="course.course_id"
										class="col-12 md:col-6 lg:col-4">
										<Card class="h-full surface-card shadow-2 border-round-xl">
											<template #header>
												<div
													class="flex justify-content-between align-items-center p-3 border-bottom-1 surface-border">
													<div class="text-xl font-bold text-primary">{{ course.course_name }}
													</div>
													<div class="flex">
														<SplitButton dropdownIcon="pi pi-bars"
															class="p-button dropdown-only p-button-text p-button-plain"
															:model="getActionMenuModel(course)">
															<i></i>
														</SplitButton>
													</div>
												</div>
											</template>
											<template #content>
												<div class="grid p-3">
													<div class="col-12">
														<div class="flex align-items-center mb-2">
															<i class="pi pi-hashtag text-500 mr-2"></i>
															<span class="text-500">课程编号</span>
														</div>
														<div class="text-900 font-medium">{{ course.course_number }}
														</div>
													</div>
													<div class="col-12">
														<div class="flex align-items-center mb-2">
															<i class="pi pi-info-circle text-500 mr-2"></i>
															<span class="text-500">课程描述</span>
														</div>
														<div class="text-900 line-height-3">{{ course.description }}
														</div>
													</div>
													<div class="col-6">
														<div class="flex align-items-center mb-2">
															<i class="pi pi-star text-500 mr-2"></i>
															<span class="text-500">学分</span>
														</div>
														<div class="text-900 font-medium">{{ course.credit_hours }}
														</div>
													</div>
													<div class="col-6">
														<div class="flex align-items-center mb-2">
															<i class="pi pi-check-circle text-500 mr-2"></i>
															<span class="text-500">状态</span>
														</div>
														<div class="text-900 font-medium">
															<Tag :value="course.status"
																:severity="course.status === 'active' ? 'success' : 'warning'" />
														</div>
													</div>
													<div class="col-12">
														<div class="flex align-items-center mb-2">
															<i class="pi pi-chart-pie text-500 mr-2"></i>
															<span class="text-500">成绩权重</span>
														</div>
														<div class="grid">
															<div class="col-12 md:col-6">
																<Chart type="pie" :data="getGradeWeightData(course)"
																	:options="chartOptions" class="w-full" />
															</div>
															<div
																class="col-12 md:col-6 flex flex-column justify-content-center">
																<div class="mb-2">
																	<div class="flex align-items-center">
																		<div class="w-2rem h-2rem border-round"
																			style="background-color: #42A5F5"></div>
																		<span class="ml-2 text-900">平时成绩</span>
																		<span class="ml-auto font-bold">{{
																			course.daily_weight*100 }}%</span>
																	</div>
																</div>
																<div class="mb-2">
																	<div class="flex align-items-center">
																		<div class="w-2rem h-2rem border-round"
																			style="background-color: #66BB6A"></div>
																		<span class="ml-2 text-900">考试成绩</span>
																		<span class="ml-auto font-bold">{{
																			course.exam_weight*100 }}%</span>
																	</div>
																</div>
																<div>
																	<div class="flex align-items-center">
																		<div class="w-2rem h-2rem border-round"
																			style="background-color: #FFA726"></div>
																		<span class="ml-2 text-900">作业成绩</span>
																		<span class="ml-auto font-bold">{{
																			course.homework_weight*100 }}%</span>
																	</div>
																</div>
															</div>
														</div>
													</div>
													
												</div>
											</template>
											<template #footer>
												<div
													class="flex justify-content-between align-items-center p-3 border-top-1 surface-border">
													<div class="flex align-items-center">
														<i class="pi pi-user text-500 mr-2"></i>
														<span class="text-500">教师ID: {{ course.teacher_id }}</span>
													</div>
													<div class="flex align-items-center">
														<i class="pi pi-clock text-500 mr-2"></i>
														<span class="text-500">{{ utils.humanDatetime(course.created_at)  }}</span>
													</div>
												</div>
											</template>
										</Card>
									</div>
								</div>
								<!-- Empty record -->
								<template v-if="pageReady && !records.length">
									<div class="p-3 my-3 text-500 text-lg font-medium text-center">
										{{ $t('noRecordFound') }}
									</div>
								</template>
								<!-- end of empty record-->
								<!-- pagination component-->
								<template v-if="showFooter && pageReady">
									<div class="grid justify-content-between align-items-center">
										<div class="flex gap-2 flex-grow-0">
											<template v-if="auth.canView('courses')">
												<div v-if="selectedItems.length" class="m-2">
													<Button @click="deleteItem(selectedItems)" icon="pi pi-trash"
														class="p-button-danger" :title="$t('deleteSelected')" />
												</div>
											</template>
										</div>
										<div v-if="paginate && totalPages > 1" class="flex-grow-1">
											<Paginator class="paginator-flat my-3" :first="recordsPosition - 1"
												@page="(event) => { pagination.page = event.page + 1 }"
												:rows="pagination.limit" :totalRecords="totalRecords">
												<template #start>
													<span class="px-2">
														{{ $t('records') }} <b>{{ recordsPosition }} {{ $t('of') }} {{
															totalRecords }}</b>
													</span>
												</template>
												<template #end>
												</template>
											</Paginator>
										</div>
									</div>
								</template>
								<!-- end of pagination component-->
							</div>
						</div>
					</div>
				</div>
			</div>
		</section>
	</main>
	<Dialog v-model:visible="showImportDialog" :style="{ width: '50vw' }" :header="$t('importCourses')" :modal="true">
		<FileUpload name="file" mode="basic" @select="onFileSelect" :multiple="false" accept=".xlsx,.xls"
			:maxFileSize="1000000" chooseLabel="选择文件" :auto="false" :showUploadButton="false" :showCancelButton="false"
			dropMessage="将文件拖放到此处上传">
		</FileUpload>

		<DataTable :value="importData" v-if="importData.length" class="mt-3">
			<Column field="course_name" header="课程名称"></Column>
			<Column field="description" header="课程描述"></Column>
			<Column field="credit_hours" header="学分"></Column>
			<Column field="daily_weight" header="平时成绩权重"></Column>
			<Column field="exam_weight" header="考试成绩权重"></Column>
			<Column field="homework_weight" header="作业成绩权重"></Column>
			<Column field="start_date" header="开始日期"></Column>
			<Column field="end_date" header="结束日期"></Column>
			<Column field="teacher_id" header="教师ID"></Column>
			<Column field="status" header="状态"></Column>
			<Column field="course_number" header="课程编号"></Column>
		</DataTable>

		<template #footer>
			<Button :label="$t('cancel')" icon="pi pi-times" @click="showImportDialog = false" class="p-button-text" />
			<Button :label="$t('confirmImport')" icon="pi pi-check" @click="confirmImport"
				:disabled="!importData.length" />
		</template>
	</Dialog>
</template>
<script setup>
import { toRefs, onMounted, ref } from 'vue';
import { usePageStore } from 'src/store/page';
import { useApp } from 'src/composables/app.js';
import { useAuth } from 'src/composables/auth';
import { $t } from 'src/services/i18n';
import { useListPage } from 'src/composables/listpage.js';
import { ApiService } from 'src/services/api';
import * as XLSX from 'xlsx';
import { useToast } from 'primevue/usetoast';
import Chart from 'primevue/chart';
import Tag from 'primevue/tag';
import { utils } from '@/utils';

const props = defineProps({
	primaryKey: {
		type: String,
		default: 'course_id',
	},
	pageStoreKey: {
		type: String,
		default: 'COURSES',
	},
	pageName: {
		type: String,
		default: 'courses',
	},
	routeName: {
		type: String,
		default: 'courseslist',
	},
	apiPath: {
		type: String,
		default: 'courses/index',
	},
	autoLoad: {
		type: Boolean,
		default: true,
	},
	enableCache: {
		type: Boolean,
		default: false,
	},
	paginate: {
		type: Boolean,
		default: true,
	},
	showHeader: {
		type: Boolean,
		default: true,
	},
	showFooter: {
		type: Boolean,
		default: true,
	},
	showBreadcrumbs: {
		type: Boolean,
		default: true,
	},
	exportButton: {
		type: Boolean,
		default: true,
	},
	importButton: {
		type: Boolean,
		default: false,
	},
	multiCheckbox: {
		type: Boolean,
		default: true,
	},
	page: {
		type: Number,
		default: 1,
	},
	limit: {
		type: Number,
		default: 6,
	},
	mergeRecords: { // for infinite loading
		type: Boolean,
		default: false,
	},
	search: {
		type: String,
		default: '',
	},
	fieldName: null,
	fieldValue: null,
	queryParams: {
		type: Object,
		default: () => ({})
	},
	sortBy: {
		type: String,
		default: '',
	},
	sortType: {
		type: String,
		default: 'desc', //desc or asc
	},
	isSubPage: {
		type: Boolean,
		default: false,
	},
	emptyRecordMsg: {
		type: String,
		default: () => $t('noRecordFound'),
	},
	titleBeforeDelete: {
		type: String,
		default: $t('deleteRecord'),
	},
	msgBeforeDelete: {
		type: String,
		default: () => $t('promptDeleteRecord'),
	},
	msgAfterDelete: {
		type: String,
		default: () => $t('recordDeletedSuccessfully'),
	},
	filterTagClass: {
		type: String,
		default: 'surface-card p-2 text-500 flex-grow-1 text-center m-1 mb-3 flex-grow-1 text-center',
	}
});

const app = useApp();
const auth = useAuth();
const toast = useToast();

const defaultStoreState = {
	filters: {
		search: {
			tag: "Search",
			value: '',
			valueType: 'single',
			options: [],
		}
	},
	pagination: {
		page: props.page,
		limit: props.limit,
		sortBy: props.sortBy,
		sortType: props.sortType
	},
	primaryKey: props.primaryKey,
	enableCache: props.enableCache
}
const store = usePageStore(props.pageStoreKey, defaultStoreState);

// page hooks where logics resides
const page = useListPage({ store, props });

const { records, filters, totalRecords, selectedItems, pagination, } = toRefs(store.state);
const { pageReady, loading, } = toRefs(page.state);

const { pageBreadCrumb, totalPages, recordsPosition, } = page.computedProps;

const { load, exportPage, debounce, onSort, deleteItem, } = page.methods;

const showImportDialog = ref(false);
const importData = ref([]);

const onFileSelect = async (event) => {
	const file = event.files[0];
	const reader = new FileReader();

	reader.onload = (e) => {
		try {
			const data = new Uint8Array(e.target.result);
			const workbook = XLSX.read(data, { type: 'array', cellDates: true });
			const sheet = workbook.Sheets[workbook.SheetNames[0]];
			const jsonData = XLSX.utils.sheet_to_json(sheet, {
				range: 1, // 跳过前两行标题
				raw: false, // 不返回原始值
				dateNF: 'yyyy-mm-dd' // 指定日期格式
			});

			importData.value = jsonData.map(row => {
				// 处理日期
				const formatDate = (date) => {
					if (!date) return null;
					if (date instanceof Date) {
						return date.toISOString().split('T')[0];
					}
					if (typeof date === 'number') {
						// Excel日期是从1900年1月1日开始的天数
						const excelDate = new Date((date - 25569) * 86400 * 1000);
						return excelDate.toISOString().split('T')[0];
					}
					// 尝试解析其他格式的日期字符串
					const parsedDate = new Date(date);
					if (!isNaN(parsedDate.getTime())) {
						return parsedDate.toISOString().split('T')[0];
					}
					return null;
				};

				return {
					course_name: row['course_name'],
					description: row['description'],
					credit_hours: parseFloat(row['credit_hours']) || 0,
					daily_weight: parseFloat(row['daily_weight']) || 0,
					exam_weight: parseFloat(row['exam_weight']) || 0,
					homework_weight: parseFloat(row['homework_weight']) || 0,
					start_date: formatDate(row['start_date']),
					end_date: formatDate(row['end_date']),
					teacher_id: row['teacher_id'],
					status: row['status'] || 'active',
					course_number: row['course_number']
				};
			});
		} catch (error) {
			console.error('文件处理错误:', error);
			toast.add({ severity: 'error', summary: '错误', detail: '文件处理失败', life: 3000 });
		}
	};

	reader.readAsArrayBuffer(file);
};

const confirmImport = async () => {
	try {
		await ApiService.post('courses/bulk-import', importData.value);
		showImportDialog.value = false;
		importData.value = [];
		toast.add({ severity: 'info', summary: '成功', detail: '文件上传成功', life: 3000 });
		load(); // 重新加载数据
	} catch (error) {
		toast.add({ severity: 'error', summary: '错误', detail: '文件上传失败', life: 3000 });
	}
};

const downloadTemplate = async () => {
	try {
		const response = await ApiService.get('courses/template', {
			responseType: 'arraybuffer'
		});
		const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
		const link = document.createElement('a');
		link.href = URL.createObjectURL(blob);
		link.download = 'courses_template.xlsx';
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		URL.revokeObjectURL(link.href);
	} catch (error) {
		toast.add({ severity: 'error', summary: '错误', detail: '下载模板失败', life: 3000 });
	}
};

function getActionMenuModel(data) {
	return [
		{
			label: () => $t('view'),
			to: `/courses/view/${data.course_id}`,
			icon: "pi pi-eye",
			visible: auth.canView('courses/view')
		},
		{
			label: () => $t('edit'),
			to: `/courses/edit/${data.course_id}`,
			icon: "pi pi-pencil",
			visible: auth.canView('courses/edit')
		},
		{
			label: () => $t('delete'),
			command: (event) => { deleteItem(data.course_id) },
			icon: "pi pi-trash",
			visible: auth.canView('courses/delete')
		}
	]
}

const chartOptions = {
	plugins: {
		legend: {
			display: false
		}
	},
	cutout: '60%'
};

function getGradeWeightData(course) {
	return {
		labels: ['平时成绩', '考试成绩', '作业成绩'],
		datasets: [
			{
				data: [course.daily_weight, course.exam_weight, course.homework_weight],
				backgroundColor: ['#42A5F5', '#66BB6A', '#FFA726'],
				hoverBackgroundColor: ['#64B5F6', '#81C784', '#FFB74D']
			}
		]
	};
}

onMounted(() => {
	const pageTitle = $t('courses');
	app.setPageTitle(props.routeName, pageTitle);
});
</script>
<style scoped></style>
